﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;
using System.Collections;
using System.Data;
using MS.InformationManagement.DAL.DTOs;
using MS.InformationManagement.Support;

namespace MS.InformationManagement.BLL.BusquedaPrestamosDocumentales
{
    public class BusquedaPrestamosDocumentales
    {
        public static List<RadicadoSearchDTO> SearchInLibrary(string IdValue, Guid CurrentListGuid, int pageIndex, int pageSize, out int totalRecords)
        {
            int startingPosition = pageIndex * pageSize;
            List<RadicadoSearchDTO> itemsFound = new List<RadicadoSearchDTO>();
            SPSiteDataQuery q = new SPSiteDataQuery();
            q.ViewFields = string.Format("<FieldRef Name='ContentType' /><FieldRef Name='{0}' /><FieldRef Name='{1}' /><FieldRef Name='{2}' /><FieldRef Name='{3}' /><FieldRef Name='{4}' /><FieldRef Name='{5}' />", CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED, CustomSiteColumns.FIELD_DOCUMENT_RADICADOR, CustomSiteColumns.FIELD_DOCUMENT_RADICADOR, CustomSiteColumns.FIELD_DOCUMENT_EXPEDIENTE_ID, CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID, CustomSiteColumns.FIELD_DOCSET_DEPARTMNET); 
            q.Lists = "<Lists BaseType='1'/>";
            q.Webs = "<Webs Scope='SiteCollection' />";
            q.Query = string.Format("<Where><Or><BeginsWith><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></BeginsWith><BeginsWith><FieldRef Name='{2}' /><Value Type='Text'>{3}</Value></BeginsWith></Or></Where>", CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID, IdValue, CustomSiteColumns.FIELD_DOCUMENT_EXPEDIENTE_ID, IdValue);

            DataTable dt = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSite = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb web = currentSite.OpenWeb())
                    {
                        dt = web.GetSiteData(q);
                        #region GetRadicados

                        SPList ListaAnulados = SPContext.Current.Web.Lists.TryGetList(GlobalConstants.LIST_ANULADOS);
                        IEnumerable<DataRow> query = from item in dt.AsEnumerable()
                                    where
                                    item["ListId"].ToString() != ListaAnulados.ToString() &&
                                    item["ListId"].ToString() != CurrentListGuid.ToString() &&
                                    item["ContentType"].ToString() == GlobalConstants.CTTN_RADICADO_INTERNO ||
                                    item["ContentType"].ToString() == GlobalConstants.CTTN_RADICADO_PERSONA ||
                                    item["ContentType"].ToString() == GlobalConstants.CTTN_RADICADO_EMPRESA ||
                                    item["ContentType"].ToString() == GlobalConstants.CTTN_RADICADO_EMPRESA_SALIDA ||
                                    item["ContentType"].ToString() == GlobalConstants.CTTN_RADICADO_PERSONA_SALIDA
                                    select item;

                        itemsFound = GetEntity(query);
                        #endregion
                    }
                }
            });

            totalRecords = itemsFound.Where(x=> x.Owner == false).Count();
            return itemsFound.Skip(startingPosition).Take(pageSize).ToList();
        }

        public static List<RadicadoSearchDTO> GetEntity(IEnumerable<DataRow> query)
        {
            List<RadicadoSearchDTO> itemsFound = new List<RadicadoSearchDTO>();
            foreach (DataRow dr in query)
            {
                string ownerRadicado = dr[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED] + "";
                if (string.IsNullOrEmpty(ownerRadicado))
                    ownerRadicado = dr[CustomSiteColumns.FIELD_DOCUMENT_RADICADOR].ToString();

                if (!string.IsNullOrEmpty(ownerRadicado))
                {
                    SPUser userOwnerRadicado = SPContext.Current.Web.EnsureUser(ownerRadicado);
                    RadicadoSearchDTO radicados = new RadicadoSearchDTO();
                    radicados.Id = dr["ID"].ToString();
                    radicados.IdList = dr["ListId"].ToString();
                    radicados.CurrentUser = userOwnerRadicado.Name;
                    radicados.IdExpediente = dr[CustomSiteColumns.FIELD_DOCUMENT_EXPEDIENTE_ID].ToString();
                    radicados.IdRadicado = dr[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString();
                    radicados.Department = GetDepartamento(dr[CustomSiteColumns.FIELD_DOCSET_DEPARTMNET].ToString());
                    
                    if (SPContext.Current.Web.CurrentUser.ID != userOwnerRadicado.ID)
                        radicados.Owner = false;
                    else
                        radicados.Owner = true;

                    itemsFound.Add(radicados);
                }
            }
            return itemsFound;
        }

        public static string GetDepartamento(string Department)
        {
            int idDepartamento = GetIdDepartamento(Department);
            if (idDepartamento == 0)
            {
                return string.Empty;
            }
            else
            {
                SPList listSecciones = SPContext.Current.Web.Lists[GlobalConstants.LIST_BIBLIOTECA_SECCION];
                SPListItem item = listSecciones.GetItemById(idDepartamento);
                return item.Title;
            }
        }

        public static int GetIdDepartamento(string Department)
        {
            int result = 0;

            if (Department.Contains("."))
            {
                result = ListHelper.TryToParse(Department.Split('.')[0]);
            }
            else
            {
                result = ListHelper.TryToParse(Department);
            }

            return result;
        }
    }
}
